﻿ using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.Right;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.Dto.Response.Dic;
using CarEdge.Infrastructure.Dto.Response.Org;
using CarEdge.Infrastructure.Dto.Response.Rights;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC;
using CarEdge.Infrastructure.IOC.Dic;
using CarEdge.Service.EFCore;
using CarEdge.Service.Interface;
using Crm.Infrastructure.Tools;
using Microsoft.EntityFrameworkCore;
using MySqlX.XDevAPI.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CarEdge.Service.Instance
{
    [Inject_]
    public class Rights_Service :Base_Service, I_Rights_Service
    {
        private readonly Rights_IOC _rights_IOC;

        public Rights_Service(Rights_IOC rights_IOC) {

            _rights_IOC = rights_IOC;
        }

        public async Task<Api_Response_Dto> Add_Right(Right_Request_Dto dto)
        {
            SysRight sysRight = new SysRight()
            {
                Rid = Config.GUID(),
                Rname = dto.name,
                RcreateTime = DateTime.Now,
                Rdesc = dto.desc,
                Rexplain = dto.explain,
                Ricon = dto.icon,
                RisBan = 0,
                RisDel = 0,
                RisMenu = dto.ismenu,
                RisPublic = 0,
                RisPublish = 0,
                Rno = dto.no,
                RparentRid = dto.parentid,
                Rstate = 0,
                Rurl = dto.url,
            };
            _rights_IOC._sys_Rights_EFCore.Add(sysRight);
           await _rights_IOC._sys_Rights_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");

        }

        public async Task<Api_Response_Dto> Ban_Right(Right_Request_Dto dto)
        {
            var iq = _rights_IOC._sys_Rights_EFCore.QueryAll(d => d.Rid == dto.id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            if(iq.Single().RisBan==0) {
                iq.Single().RisBan = 1;
            }
            else
            {
                iq.Single().RisBan = 0;
            }
            _rights_IOC._sys_Rights_EFCore.Update(iq.Single());
           await _rights_IOC._sys_Rights_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> Delete_Right(Right_Request_Dto dto)
        {
            var iq = _rights_IOC._sys_Rights_EFCore.QueryAll(d => d.Rid == dto.id);
            if ( !iq.Any()) {
                return Result(0, "参数错误");
            }
            var count = _rights_IOC._sys_Rights_EFCore.QueryAll(d => d.RparentRid == dto.id).ToList().Count();
            if( count > 0 )
            {
                return Result(0, "该权限存在子权限");
            }
            var right=iq.Single();
       
            _rights_IOC._sys_Rights_EFCore.Delete(right);
            await _rights_IOC._sys_Rights_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> GetAllConfig(int page, int limit, string key)
        {
            var iq = _rights_IOC._sys_Right_Config_EFCore.QueryAll(out int total, page, limit, false, o => o.RccreateTime, d => d.Rcname!.Contains(key) || d.Rcdesc!.Contains(key));


            var data = await iq.Select(d => new Right_Config_Response_Dto
            {
                id = d.Rcid,
                name = d.Rcname,
              
                time = d.RccreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
               isban=d.RcisBan,
                count = d.Rccount,
            }).ToListAsync();

            //查询出来的数据在内存中 占用空间一般来说非常小
           
            return Result(1, "ok", new
            {
                total,
                data
            });
        }

        public async Task<Api_Response_Dto> GetAllRights()
        {

            var rights = await _rights_IOC._sys_Rights_EFCore.QueryAll().ToListAsync();

            List<User_Rights_Response_Dto> data = new List<User_Rights_Response_Dto>();

            var root = rights.Where(d => d.RparentRid == null || d.RparentRid == "").OrderBy(d => d.Rno).ToList();
            root.ForEach(d =>
            {
               
                    data.Add(new User_Rights_Response_Dto
                    {
                        id = d.Rid,
                        name = d.Rname,
                        url = string.IsNullOrEmpty(d.Rurl) ? "" : d.Rurl,
                        icon = d.Ricon,
                        children = GetChildrenRights(d.Rid, rights)
                    });
                
               
            });
            return Result(1, data: data);
        }

        public async Task<Api_Response_Dto> GetAllUserRight(int page, int limit, string key)
        {
            var iq = _rights_IOC._sys_User_EFCore.QueryAll(out int total, page, limit, false, o => o.UcreateTime, d => d.Uname!.Contains(key) || d.Udesc!.Contains(key));

            List<User_Rights_Response_Dto> list = new List<User_Rights_Response_Dto>();
            var data = await iq.Select(d => new User_Org_Response_Dto
            {
                id = d.Uid,
                name = d.Uname,
                depname=d.Udept,
                createtime = d.UcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                isBan = d.UisBan,
                dutyname = d.Uduty,
                isActive = d.UisActive,
                Ugender = d.Ugender,
                account=d.Uaccount,
            
            }).ToListAsync();
            data.ForEach(d =>
            {
                d.depname = _rights_IOC._sys_Department_EFCore.QueryAll(e => e.Did == d.depname).FirstOrDefault()!.Dname;
                d.dutyname = _rights_IOC._sys_Duty_EFCore.QueryAll(e => e.Did == d.dutyname).FirstOrDefault()!.Dname;
                d.rights = this.Get_Menus2(d.id);
            });

            //查询出来的数据在内存中 占用空间一般来说非常小

            return Result(1, "ok", new
            {
                total,
                data
            });
        }

        public async Task<Api_Response_Dto> GetRightById(string id)
        {
           var iq=_rights_IOC._sys_Rights_EFCore.QueryAll(d=>d.Rid == id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            var right = await iq.SingleAsync();


            User_Rights_Response_Dto user_Rights_Response_Dto = new User_Rights_Response_Dto()
            {
                name = right.Rname,
                icon = right.Ricon,
                url = right.Rurl,
                explain = right.Rexplain,
                no = right.Rno,
                ismenu=right.RisMenu
            };

            return Result(1,data: user_Rights_Response_Dto);
        }

        public async Task<Api_Response_Dto> GetRightsByUid(string id)
        {
          var user=_rights_IOC._sys_User_EFCore.QueryAll(d=>d.Uid == id);
            if (!user.Any())
            {
                return Result (0, "参数错误");
            }
            List<string> list = new List<string>();
            List<User_Rights_Response_Dto> user_Rights_Response_Dtos = new List<User_Rights_Response_Dto>();
            var rights= _rights_IOC._sys_User_Right_EFCore.QueryAll(d => d.Uruid == id).ToList();
            rights.ForEach(d =>
            {
                if (_rights_IOC._sys_Rights_EFCore.QueryAll(a => a.RparentRid == d.Urrid).Count() == 0)
                {              
                User_Rights_Response_Dto user_Rights_Response_Dto = new User_Rights_Response_Dto()
                {
                    id = d.Urrid,
                    //name =  _rights_IOC._sys_Rights_EFCore.QueryAll(e => e.Rid == d.Urrid).Select(d => d.Rname).FirstOrDefault(),
                };
                user_Rights_Response_Dtos.Add(user_Rights_Response_Dto);
                list.Add(d.Urrid!);
                }
            });
            await _rights_IOC._sys_Rights_EFCore.SaveChangesAsync();
            return Result(1, "操作成功",data:list);
        }

        private List<User_Rights_Response_Dto> Get_Menus2(string uid)
        {
            //用户的权限
            var userRight =  _rights_IOC._sys_User_Right_EFCore.QueryAll(d => d.Uruid == uid).ToList();
            //权限id
            var rids = userRight.Select(d => d.Urrid).ToList();

            var rights =  _rights_IOC._sys_Rights_EFCore.QueryAll(d => rids.Contains(d.Rid)).ToList();

            List<User_Rights_Response_Dto> data = new List<User_Rights_Response_Dto>();

            var root = rights.Where(d => d.RparentRid == null || d.RparentRid == "").OrderBy(d => d.Rno).ToList();

            root.ForEach(d =>
            {
                data.Add(new User_Rights_Response_Dto
                {
                    id = d.Rid,
                    name = d.Rname,
                    url = string.IsNullOrEmpty(d.Rurl) ? Config.GUID2() : d.Rurl,
                    icon = d.Ricon,
                    children = GetChildrenRights(d.Rid, rights)
                });
            });
            return data;

        }

        /// <summary>
        /// 获取用户所拥有的权限菜单
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Get_Menus(string uid)
        {
           //用户的权限
            var userRight=await _rights_IOC._sys_User_Right_EFCore.QueryAll(d=>d.Uruid==uid).ToListAsync();
           //权限id
            var rids=userRight.Select(d=>d.Urrid).ToList();

            var rights =await _rights_IOC._sys_Rights_EFCore.QueryAll(d => rids.Contains(d.Rid)).ToListAsync();

            List<User_Rights_Response_Dto> data = new List<User_Rights_Response_Dto>();

            var root = rights.Where(d => d.RparentRid == null || d.RparentRid=="").OrderBy(d=>d.Rno).ToList();

            root.ForEach( d =>
            {
                data.Add(new User_Rights_Response_Dto
                {
                    id = d.Rid,
                    name = d.Rname,
                    url = string.IsNullOrEmpty(d.Rurl)?Config.GUID2():d.Rurl,
                    icon = d.Ricon,
                    children = GetChildrenRights(d.Rid, rights)
                });
            });
            return Result(1,data:data);

        }

        public async Task<Api_Response_Dto> Give_Rights(Right_Request_Dto dto)
        {
            var oldrights= _rights_IOC._sys_User_Right_EFCore.QueryAll(d => d.Uruid == dto.id).ToList();
            _rights_IOC._sys_User_Right_EFCore.DeleteRange(oldrights);
            dto.ids!.ForEach(d =>
            {
                SysUserRight sys_User_EFCore = new SysUserRight()
                {
                    Urid = Config.GUID2(),
                    UrbeginTime = null,
                    UrcreateTime = DateTime.Now,
                    Urdesc = null,
                    UroutTime = null,
                    Urrid = d,
                    Uruid = dto.id
                };
                _rights_IOC._sys_User_Right_EFCore.Add(sys_User_EFCore);
            });
         var result=   await _rights_IOC._sys_User_Right_EFCore.SaveChangesAsync();
            return Result(1,"操作成功",data:dto);
           
        }

        public async Task<Api_Response_Dto> Update_Right(Right_Request_Dto dto)
        {
            var iq = _rights_IOC._sys_Rights_EFCore.QueryAll(d => d.Rid == dto.id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            var right = iq.Single();
            right.Rname = dto.name;
            right.Ricon = dto.icon;
            right.Rexplain = dto.explain;
            right.Rno = dto.no;
            right.Rurl = dto.url;
            right.RisMenu=dto.ismenu;
            _rights_IOC._sys_Rights_EFCore.Update(right);
            await _rights_IOC._sys_Rights_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        /// <summary>
        /// 获取子级
        /// </summary>
        /// <param name="rid"></param>
        /// <param name="rights"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<User_Rights_Response_Dto> GetChildrenRights(string rid, List<SysRight> rights)
        {

            var children=rights.Where(d=>d.RparentRid==rid).OrderBy(d=>d.Rno).ToList();
            List<User_Rights_Response_Dto> data=new List<User_Rights_Response_Dto>();
            children.ForEach(d =>
            {

                data.Add(new User_Rights_Response_Dto
                {
                    id = d.Rid,
                    name = d.Rname,
                    url = string.IsNullOrEmpty(d.Rurl)?Config.GUID2():d.Rurl,
                    icon = d.Ricon,
                    children = GetChildrenRights(d.Rid, rights)
                });
            });
            return data;

        }
    }
}
